<?php
/**
 * HTTP接口调用类
 * @文件名称: Curl.php
 * @author: jawei
 * @Email: gaozhiwei@etcp.cn
 * @Date: 2017-06-06
 * @Copyright: 2017 悦畅科技有限公司. All rights reserved.
 * 注意：本内容仅限于悦畅科技有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
namespace app\lib;
use Yii;
use yii\base\ErrorException;
class Curl {
    /**
     * HTTP接口调用
     * @param  string  method  请求方法
     * @param  string  url     接口地址
     * @param  array   param   请求参数
     * @param  array   header  其他HTTP请求头
     * @param  integer timeout 响应超时时间
     * @return string  response
     */
    public static function curlRequest($method, $url, $param = array(), $header = array(), $timeout = 5)
    {
        $defaults = [
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 RRX Agent',
            CURLOPT_HEADER => 0,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_CONNECTTIMEOUT => $timeout,
            CURLOPT_TIMEOUT => $timeout
        ];

        $options = [];

        if (sizeof($header) > 0) {
            $options[CURLOPT_HTTPHEADER] = $header;
        }

        if (strtolower($method) == 'post') {
            $options[CURLOPT_URL] = $url;
            $options[CURLOPT_POST] = 1;
            if (is_array($param)) {
                $options[CURLOPT_POSTFIELDS] = http_build_query($param);
            } else {
                $options[CURLOPT_POSTFIELDS] = $param;
            }
        } else {
            if (strpos($url, '?') !== False) {
                $options[CURLOPT_URL] = $url . '&' . http_build_query($param);
            } else {
                $options[CURLOPT_URL] = $url . '?' . http_build_query($param);
            }
        }
        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));

        if(!$result = curl_exec($ch)) {
            $errno = curl_errno($ch);
            throw new ErrorException("Curl error [$errno]: " . curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }
}
